<template>
  <div>
        <!-- 搜索栏 -->
        <search-bar />

<!-- 添加商品 -->
<add-product />
    <!-- 商品筛选器 -->
    

    <!-- 商品列表 -->
    <product-list
      v-if="paginatedProducts.length > 0"
      :products="paginatedProducts"
      :current-page="currentPage"
      :page-size="pageSize"
      :total-products="filteredProducts.length"
      @page-change="handlePageChange"
    />
        <!-- 跳转到库存管理页面的按钮 -->
        <el-button type="primary" @click="goToInventory" style="margin-top: 20px;">
      跳转到库存管理页面
    </el-button>

    <!-- 导航菜单 -->
    <el-menu mode="horizontal" router>
      <el-menu-item index="/">主界面</el-menu-item>
      <el-menu-item index="/inventory">库存管理</el-menu-item>
    </el-menu>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useProductStore } from '../stores/productStore';

import SearchBar from '../components/SearchBar.vue';
import AddProduct from '../components/AddProduct.vue';
import ProductList from '../components/ProductList.vue';
import ProductFilter from '../components/ProductFilter.vue';
import { useRouter } from 'vue-router';

export default {

  components: {
    SearchBar,
    AddProduct,
    ProductList,
    ProductFilter,
  },
  setup() {
    const router = useRouter();
    

    const store = useProductStore();

    // 品牌数据
    const brands = computed(() => store.brands);

    // 筛选后的商品
    const filteredProducts = computed(() => store.filteredProducts);

    // 当前页码
    const currentPage = ref(1);

    // 每页显示的商品数量
    const pageSize = ref(10);

    // 当前页的商品
    const paginatedProducts = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredProducts.value.slice(start, end);
    });

    // 筛选逻辑
    const handleFilter = (filter) => {
      store.updateFilter(filter); // 更新筛选条件到 store
      currentPage.value = 1; // 重置当前页码为第一页
    };

    // 处理分页变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };

    
    const goToInventory = () => {
      router.push({ name: 'Inventory' }); // 跳转到库存管理页面
    };

    // 初始化商品数据
    onMounted(() => {
      store.fetchProducts(); // 确保数据加载
    });

    return {
      brands,
      filteredProducts,
      paginatedProducts,
      currentPage,
      pageSize,
      handleFilter,
      handlePageChange,
      goToInventory,
    };
  },
};
</script>
